﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using ModeloGaleriaNET;

namespace GaleriaNET
{
    /// <summary>
    /// Lógica de interacción para ChooseWinnerWindow.xaml
    /// </summary>
    public partial class ChooseWinnerWindow : Window
    {
        private readonly int pageSize = 10;
        private int pagenum;
        private int numPujas;
        private BackgroundWorker worker;
        private Subasta subasta;
        ModeloGaleriaNET.SubastasQueries.SubastasQueries query;
        ModeloGaleriaNET.SubastasQueries.AuthInfo auth;
        List<DataGridPujaProxy> pujas;
        private long winner;
        private bool success;
        private bool llamadaCorrecta;

        public ChooseWinnerWindow()
        {
            InitializeComponent();
        }

        public ChooseWinnerWindow(Subasta s)
        {
            InitializeComponent();
            subasta = s;
            auth = new ModeloGaleriaNET.SubastasQueries.AuthInfo();
            auth.password = Utilities.EncriptarMD5(ServerConnData.Instance.Password);
            auth.pseudonimo = ServerConnData.Instance.User;
            query = new ModeloGaleriaNET.SubastasQueries.SubastasQueries();
            query.Timeout = (int)ServerConnData.Instance.TimeOut * 1000;
            worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            pujas = new List<DataGridPujaProxy>();
            pagenum = 0;
        }

        public long Winner
        {
            get { return winner; }
        }

        public bool Success
        {
            get { return success; }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (worker.IsBusy == false)
            {
                _busyIndicator.IsBusy = true;
                worker.RunWorkerAsync();
            }
        }

        private void buscarPujas()
        {
            ModeloGaleriaNET.SubastasQueries.SubastaProxy[] subastas;
            ModeloGaleriaNET.SubastasQueries.SubastaProxy sub;
            
            subastas = query.listarSubastadasPorUsuario(auth)
                .Where(s => s.referencia == Convert.ToInt64(subasta.ReferenciaExterna)).ToArray();
            
            if (subastas != null && subastas.Count() > 0)
            {
                sub = subastas.First();
                if (sub.pujas != null && sub.pujas.Count() > 0)
                {
                    // ----------------------------------------------------------->
                    foreach (ModeloGaleriaNET.SubastasQueries.PujaProxy p in sub.pujas)
                        pujas.Add(new DataGridPujaProxy(Convert.ToInt32(p.numeroExterno), (int)p.numero, p.fecha.Value, p.cantidad, p.postor));
                    // ----------------------------------------------------------->

                    pujas = pujas.OrderByDescending(p => p.FechaSort).ToList();
                }
            }
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                buscarPujas();
                llamadaCorrecta = true;
            }
            catch (Exception)
            {
                try
                {
                    jUDDIManager.Instance.UpdateURL();
                    buscarPujas();
                    llamadaCorrecta = true;
                }
                catch (Exception)
                {
                    llamadaCorrecta = false;
                }
            }
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            _busyIndicator.IsBusy = false;
            if (llamadaCorrecta)
            {
                numPujas = pujas.Count;
                pagenum = 0;
                SetDataGridSource();
                UpdatePaginationControls();
            }
            else
                Xceed.Wpf.Toolkit.MessageBox.Show("No se han podido extraer las pujas de esta subasta",
                        "Error", MessageBoxButton.OK, MessageBoxImage.Error);

        }

        private void btCancelar_Click(object sender, RoutedEventArgs e)
        {
            success = false;
            Close();
        }

        private void btAceptar_Click(object sender, RoutedEventArgs e)
        {
            DataGridRow dgr;

            if (sender != null)
            {
                if (dgPujas != null && dgPujas.SelectedItems != null && dgPujas.SelectedItems.Count == 1)
                {
                    dgr = dgPujas.ItemContainerGenerator.ContainerFromItem(dgPujas.SelectedItem) as DataGridRow;
                    if (dgr.Item is DataGridPujaProxy)
                    {
                        if (Xceed.Wpf.Toolkit.MessageBox.Show("¿Desea declarar como ganadora esta puja?",
                            "Declarar ganadora", MessageBoxButton.YesNo, MessageBoxImage.Question)
                            == MessageBoxResult.Yes)
                        {
                            winner = ((DataGridPujaProxy)dgr.Item).IdCore;
                            success = true;
                            Close();
                        }
                        else
                            return;
                    }
                }
                else
                {
                    Xceed.Wpf.Toolkit.MessageBox.Show("Debes seleccionar una puja", "Error",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    success = false;
                    return;
                }
            }
            else
                success = false;
        }

        private void SetDataGridSource()
        {
            int inicio;
            List<DataGridPujaProxy> source;

            source = new List<DataGridPujaProxy>();
            inicio = pagenum * pageSize;
            dgPujas.ItemsSource = null;
            dgPujas.Items.Clear();

            for (int i = inicio; i < pujas.Count && i < inicio + pageSize; i++)
                source.Add(pujas[i]);

            dgPujas.ItemsSource = source;
        }

        private void btAnterior_Click(object sender, RoutedEventArgs e)
        {
            pagenum--;
            SetDataGridSource();
            UpdatePaginationControls();
        }

        private void btAnterior_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            IntPtr b;
            BitmapSource bs;

            if (imgBtAnterior != null)
            {
                b = Convert.ToBoolean(e.NewValue) ? Properties.Resources.Left_24.GetHbitmap() : Properties.Resources.LeftBW_24.GetHbitmap();
                bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                  System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                this.imgBtAnterior.Source = bs;
            }
        }

        private void btSiguiente_Click(object sender, RoutedEventArgs e)
        {
            pagenum++;
            SetDataGridSource();
            UpdatePaginationControls();
        }

        private void btSiguiente_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            IntPtr b;
            BitmapSource bs;

            if (imgBtSiguiente != null)
            {
                b = Convert.ToBoolean(e.NewValue) ? Properties.Resources.Right_24.GetHbitmap() : Properties.Resources.RightBW_24.GetHbitmap();
                bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                  System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                this.imgBtSiguiente.Source = bs;
            }
        }

        private void UpdatePaginationControls()
        {
            String iniString = "0";
            String deString = string.Empty;

            if (numPujas > 0)
                iniString = (pagenum * pageSize + 1).ToString();

            btAnterior.IsEnabled = pagenum == 0 ? false : true;

            if (pagenum + 1 >= numPujas / (float)pageSize)
            {
                btSiguiente.IsEnabled = false;
                deString = numPujas.ToString();
            }
            else
            {
                btSiguiente.IsEnabled = true;
                deString = ((pagenum + 1) * pageSize).ToString();
            }

            lbPagina.Content = iniString + " - " + deString + " de " + numPujas;
        }
    }

    public class DataGridPujaProxy
    {
        private int id;
        private int idCore;
        private DateTime fecha;
        private double cantidad;
        private string autor;

        public DataGridPujaProxy()
        {
            id = idCore = -1;
            autor = string.Empty;
            fecha = DateTime.Now;
            cantidad = -1.0D;
        }

        public DataGridPujaProxy(int id, int idCore, DateTime fecha, double cantidad, string autor)
        {
            this.id = id;
            this.idCore = idCore;
            this.fecha = fecha;
            this.cantidad = cantidad;
            this.autor = autor;
        }

        public int Id
        {
            get { return id; }
        }

        public int IdCore
        {
            get { return idCore; }
        }

        public string Autor
        {
            get { return autor; }
        }

        public DateTime FechaSort
        {
            get { return fecha; }
        }

        public string Fecha
        {
            get { return String.Format("{0:dd MMMM yyyy, HH:mm:ss}", fecha); }
        }

        public string Cantidad
        {
            get { return cantidad.ToString() + " €"; }
        }
    }
}
